<template>
    <div ref="editorContainer"></div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'

const props = defineProps({
    modelValue: {
        type: String,
        default: ''
    },
    options: {
        type: Object,
        default: () => ({})
    }
})

const emit = defineEmits(['update:modelValue'])

const editorContainer = ref(null)
const editor = ref(null)

const defaultOptions = {
    theme: 'snow',
    modules: {
        toolbar: [
            [{ header: [1, 2, 3, false] }],
            ['bold', 'italic', 'underline'],
            [{ list: 'ordered' }, { list: 'bullet' }],
            [{ color: [] }, { background: [] }],
            [{ align: [] }],
            ['clean'],
            ['link'] // 移除了 image 和 video
        ]
    },
    placeholder: '在这里输入内容...'
}

// 合并默认选项和传入的选项
const editorOptions = {
    ...defaultOptions,
    ...props.options
}

onMounted(async () => {
    // 动态导入 Quill，确保只在客户端加载
    if (import.meta.client) {
        const Quill = await import('quill')
        await import('quill/dist/quill.core.css')
        await import('quill/dist/quill.snow.css')

        editor.value = new Quill.default(editorContainer.value, editorOptions)

        // 设置初始内容
        if (props.modelValue) {
            editor.value.root.innerHTML = props.modelValue
        }

        // 监听内容变化
        editor.value.on('text-change', () => {
            const html = editor.value.root.innerHTML
            emit('update:modelValue', html)
        })
    }
})

onBeforeUnmount(() => {
    if (editor.value) {
        editor.value.off('text-change')
    }
})

// 监听 modelValue 变化，更新编辑器内容
watch(() => props.modelValue, (newValue) => {
    if (editor.value && editor.value.root.innerHTML !== newValue) {
        editor.value.root.innerHTML = newValue
    }
})
</script>

<style>
/* 可以在这里添加自定义样式 */
.ql-container {
    min-height: 200px;
}
</style>